#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 2e5 + 5;

int n, m;
string res;
struct Node {
  char c;
  int k;
  int res;
};
string get_res(int k) {
  if (k == 0) return "O(1)";
  stringstream ss;
  ss << "O(n^" << k << ')';
  return ss.str();
}
int add(int k0, int k1) {
  if (k0 == -1)
    return 0;
  else
    return k0 + k1;
}
void parse(string s, char& c, int& k) {
  stringstream ss(s);
  string f, x, y;
  ss >> f >> c >> x >> y;
  if (x == "n" && y == "n")
    return;
  else if (x == "n")
    k = -1;
  else if (y == "n")
    k = 1;
  else {
    if (x.size() > y.size() || x.size() == y.size() && x > y) k = -1;
  }
}
void solve() {
  cin >> n >> res;
  string s;
  getline(cin, s);
  int ins[128] = {0};
  stack<Node> st;
  bool err = false;
  int mx = 0;
  rep(i, 1, n) {
    getline(cin, s);
    if (s[0] == 'F') {
      char c;
      int k = 0;
      parse(s, c, k);
      st.push(Node{c, k, max(0, k)});
      if (ins[c]) err = true;
      ins[c] = 1;
    } else {
      if (st.empty()) {
        err = true;
        continue;
      }
      Node cur = st.top();
      st.pop();
      ins[cur.c] = 0;
      if (st.empty()) {
        mx = max(mx, cur.res);
      } else {
        st.top().res = add(st.top().k, cur.res);
      }
    }
  }
  if (st.size()) err = true;
  if (err) {
    cout << "ERR" << endl;
  } else {
    if (res == get_res(mx)) {
      cout << "Yes" << endl;
    } else
      cout << "No" << endl;
  }
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}